#include <QtSerialPort/QSerialPort>
#include <QTime>
#include <QDebug>
#include "recvthread.h"
#include "mysingleton.h"

QT_USE_NAMESPACE

RecvThread::RecvThread(QObject *parent)
    : QThread(parent), waitTimeout(0), quit(false), serial_cnt(0)
{
    qDebug() << "RecvThread construct " << this->currentThreadId();
    mTimer = new QTimer();  //not QTimer(this)
    connect(mTimer, SIGNAL(timeout()), this, SLOT(timer_Handle()));
    mTimer->start(2000);
}

RecvThread::~RecvThread()
{
    mutex.lock();
    quit = true;
    mutex.unlock();
    wait();
}

void RecvThread::startRecv(QSerialPort *port, int waitTimeout)
{

    QMutexLocker locker(&mutex);
    this->port = port;
    this->waitTimeout = waitTimeout;

    if (!isRunning())
        start();
}

void RecvThread::run()
{
    while (!quit)
    {
        if (port->waitForReadyRead(waitTimeout))
        {
            // read request
            QByteArray requestData = port->readAll();
            while (port->waitForReadyRead(10))
                requestData += port->readAll();

            QString receive(requestData);
            emit this->recvOk(receive);

            serial_cnt += receive.length();
        }
        else
        {
            emit timeout(tr("Wait read request timeout %1")
                         .arg(QTime::currentTime().toString()));
        }
    }
}

void RecvThread::timer_Handle()
{
    static unsigned int cc = 0;

    if(cc != serial_cnt)
        qDebug() << "RecvThread timer id:" << this->currentThreadId() << " " << cc << " : " << serial_cnt;
    cc = serial_cnt;
}
